<?php
namespace Home\Controller;
use Common\Lib\User;
use Home\Model\DepartmentModel;
use Home\Model\RoleModel;

class DailyrecruitmentController extends CommonController {
	protected $table="RecruitInfo";
	protected $pageSize = 13;


	public function index (){
		$D = D('RbacUser');
		 //获取所有CRM部门 (二维)
        $getalldepartments_url = "Department/getAllDepartments";
	    $alldepartments = json_decode(http_get($getalldepartments_url),true);

		//$this->assign("roleList", $this->getRoles());
		$this->assign("groupList", D('Group')->where(array('status'=>1))->select());
		$this->assign("sexType", array("未定义", "男", "女"));
		$ename = $this->getRoleEname();
    	$this->assign('viewDecorator', D("Department")->decoratorView($ename));

    	//部门选项权限
    	$ename=$this->getRoleEname();

      
    	$this->assign('depart_id', $this->getDepartmentId());
    	$this->assign('departmentItem', $this->setEmployeeDepartemtnItem());
    	$this->assign('allRoles', D('Role')->getField('id,name', true));
       /* 我加的 开始*/
    	$this->assign("userNames", D("User")->getUserNames());
    	$this->assign("departmentNames", D("Department")->getDepartmentsNames());
    	$this->assign("sexType", array("未定义", "男", "女"));
    	$this->assign("sourcesType", array("2"=>"58同城", "3"=>"赶集", "4"=>"智联", "5"=>"前程", "6"=>"简历交换", "7"=>"BOSS直聘", "8"=>"内部推荐", "9"=>"其他"));
    	$this->assign('departments', D('Department')->getAllDepartments('id,name'));
    	$this->assign("sourcesList",array(array("id"=>"2","name"=>"58同城"),array("id"=>"3","name"=>"赶集"),array("id"=>"4","name"=>"智联"),array("id"=>"5","name"=>"前程"),array("id"=>"6","name"=>"简历交换"),array("id"=>"7","name"=>"BOSS直聘"),array("id"=>"8","name"=>"内部推荐"),array("id"=>"9","name"=>"其他")));
    	
    	$this->assign("testType", array("1"=>"初试已过", "2"=>"初试未过"));
    	$this->assign("testList", array(array("id"=>"1", 'name'=>"初试已过"), array("id"=>"2", "name"=>"初试未过")));
    	$this->assign("retestType", array("1"=>"复试已过", "2"=>"复试未过"));
    	$this->assign("retestList", array(array("id"=>"1", 'name'=>"复试已过"), array("id"=>"2", "name"=>"复试未过")));
        $this->assign("statusList", array(array("id"=>"1", 'name'=>"入职"), array("id"=>"2", "name"=>"试用期离职")));
    	$this->assign("statusType", array("1"=>"入职", "2"=>"试用期离职"));
    	$this->assign("recommendList", array(array("id"=>"1", 'name'=>"非内部推荐"), array("id"=>"2", "name"=>"内部推荐")));
    	$this->assign('user_role_id', session('account')['userInfo']['role_id']);
    	//获取crm的部门，职能 start
    	$this->assign('allDepartmentsList',$alldepartmentsList["list"]);//一维
    	$this->assign('allDepartments',$alldepartments["list"]);//二维
    	//获取crm的部门，职能 end
    	/* 我加的 结束*/
		$this->display();
	}

	public function setQeuryCondition() {
			$department_id = I('get.department_id');
			/*echo 'ss';
			print_r($department_id);
			echo 'kk';*/
			$user_id = session('account')['userInfo']['user_id'];
			switch(session('account')['userInfo']['role_id']){
				case 18:
				if(!empty($department_id)){
					$this->M->where(array('department_id'=>$department_id,'recruit_type'=>'1'))->order("id desc");
				}else{
					$this->M->where('recruit_type = 1')->order("id desc");
				}
			    break;
			    default :
			    $this->M->where(array('department_id'=>session('account')['userInfo']['department_id'],'user_id'=>$user_id,'recruit_type'=>'1'))
			        ->order("id desc");
			}
			if (isset($_GET['name'])) {
			$this->M->where(array('name'=>array('like', I('get.name')."%")));
		    }
		    if (isset($_GET['recommend'])) {
		    		$this->M->where(array('recommend'=>$_GET['recommend']));
            }
		    if (isset($_GET['first_test'])) {
		    		$this->M->where(array('first_test'=>$_GET['first_test']));
            }
            if (isset($_GET['retest'])) {
		    		$this->M->where(array('retest'=>$_GET['retest']));
            }
            if (isset($_GET['status'])) {
		    		$this->M->where(array('status'=>$_GET['status']));
            }
             if (isset($_GET['info_sources'])) {
		    		$this->M->where(array('info_sources'=>$_GET['info_sources']));
            }

	}

	private function getDepartmentRow(){
		if (!isset($this->departmentRow)) {
			$this->departmentRow = D('Department')->find($this->getDepartmentId());
		}
		return $this->departmentRow;
	}

	private function isHrDeparment(){
		$this->getDepartmentRow();
		
		if ($this->departmentRow['type'] == DepartmentModel::HR_DEPARTMENT) {
			return true; //$_POST['department_id'] = 0;
		} else {
			return false; //$_POST['department_id'] = session('account')['userInfo']['department_id'];
		}
	}

	private function getDepartmentId(){
		// var_dump(session('account')['userInfo']['department_id']);
		if ($this->getRoleEname()=='gold') {
			return 0;
		} else {
			$depart_id = session('account')['userInfo']['department_id'];
			
			if ($depart_id == 0) {
				return 9999999;
			} else {
				return $depart_id;
			}
		}
		
	}

	

	/**
	* 预处理
	*/
	public function _before_add(){
		$this->rightProcted();	
	}

	/**
	* 添加
	*/
	public function add(){
		$_POST["graduation_date"] = empty($_POST["graduation_date"])?"":UTC_to_locale_time($_POST["graduation_date"]);
		$_POST["resume_entry_date"] = empty($_POST["resume_entry_date"])?"":UTC_to_locale_time($_POST["resume_entry_date"]);
		$_POST["resume_quit_date"] = empty($_POST["resume_quit_date"])?"":UTC_to_locale_time($_POST["resume_quit_date"]);
		$_POST["interviewer_date"] = empty($_POST["interviewer_date"])?"":UTC_to_locale_time($_POST["interviewer_date"]);
		$_POST["retest_interviewer_date"] = empty($_POST["retest_interviewer_date"])?"":UTC_to_locale_time($_POST["retest_interviewer_date"]);
	    $_POST["recruit_type"] = 1;
	    $_POST['department_id'] = session('account')['userInfo']['department_id'];
	    $_POST['user_id'] = session('account')['userInfo']['user_id'];
		/*if(session('account')['userInfo']['department_id']!=0){
			$_POST['department_name'] =D("Department")->getDepartment(session('account')['userInfo']['department_id']);	
		}*/
		if($_POST["info_sources"] == 8){
			if(empty($_POST["recommend_name"])){
				$this->error("选择内部推荐必须填写推荐人！");
			    exit();
			}
		}else{
				if(!empty($_POST["recommend_name"])){
				$this->error("填写推荐人必须选择内部推荐！");
			    exit();
			}
		}
		if(!empty($_POST["resume_entry_date"])&&empty($_POST["resume_quit_date"])|| !empty($_POST["resume_quit_date"])&&empty($_POST["resume_entry_date"])){
			$this->error("请输入任职的开始和结束日期！");
			exit();
		}
		if($_POST["resume_entry_date"]>$_POST["resume_quit_date"]){
			$this->error("任职的开始日期不能大于结束日期！");
			exit();
		}
		if($_POST["first_test"] == 1){
			if(!empty($_POST["retest_interviewer_date"])){
					if(!start_end_date($_POST["interviewer_date"],$_POST["retest_interviewer_date"])){
						$this->error("复试日期不能小于初试日期！");
						exit();
					}
			}else{
				$this->error("初试已过，复试日期不能为空！");
			    exit();
			}
		}
		if(add_field_unique("recruit_info",session('account')['userInfo']['department_id'],"mphone",$_POST["mphone"])){
			$this->error("该应聘人员的信息已录入！");
			exit();
		}
		$re = $this->M->create($_POST, 1);
		if ($re) {
			$this->M->startTrans(); 
			$re['recruitInfo'] = M('recruitInfo')->create($_POST, 1);
			$id = $this->M->add($re);
			if ($id) {
					$this->M->commit();
					$this->success(L('ADD_SUCCESS'));
			} else {
				$this->M->rollback();
				$this->error($this->M->getError());
			}
		} else {
			$this->error($this->M->getError());
		}

	}



	/**
	* 编辑
	*/
		public function edit(){
		//新方法
		$_POST["graduation_date"] = $_POST["graduation_date"] == "0000-00-00"?"":UTC_to_locale_time($_POST["graduation_date"]);
		$_POST["resume_entry_date"] =$_POST["resume_entry_date"] =="0000-00-00"?"":UTC_to_locale_time($_POST["resume_entry_date"]);
		$_POST["resume_quit_date"] =$_POST["resume_quit_date"] =="0000-00-00"?"":UTC_to_locale_time($_POST["resume_quit_date"]);
		$_POST["interviewer_date"] = $_POST["interviewer_date"] =="0000-00-00" ?"":UTC_to_locale_time($_POST["interviewer_date"]);
		$_POST["retest_interviewer_date"] = $_POST["retest_interviewer_date"] =="0000-00-00" ?"":UTC_to_locale_time($_POST["retest_interviewer_date"]);
        if(!empty($_POST["resume_entry_date"])&&empty($_POST["resume_quit_date"])|| !empty($_POST["resume_quit_date"])&&empty($_POST["resume_entry_date"])){
			$this->error("请输入任职的开始和结束日期！");
			exit();
		}
		if($_POST["resume_entry_date"]>$_POST["resume_quit_date"]){
			$this->error("任职的开始日期不能大于结束日期！");
			exit();
		}
	/*	if(!start_end_date($_POST["interviewer_date"],$_POST["retest_interviewer_date"])){
			$this->error("复试日期不能小于初试日期！");
			exit();
		}*/

		if($_POST["first_test"] == 1){
			if(!empty($_POST["retest_interviewer_date"])){
					if(!start_end_date($_POST["interviewer_date"],$_POST["retest_interviewer_date"])){
						$this->error("复试日期不能小于初试日期！");
						exit();
					}
			}else{
				$this->error("初试已过，复试日期不能为空！");
			    exit();
			}
		}
        if(edit_field_unique("recruit_info",session('account')['userInfo']['department_id'],"mphone",$_POST["mphone"],$_POST["id"])){
			$this->error("该应聘人员的信息已录入！");
			exit();
		}
        $re = M('recruitInfo')->create($_POST, 2);
		if ($re) {
			if (M('recruitInfo')->where(array('id'=>I('post.id') ))->save() !== false) {
				$this->success(L('ADD_SUCCESS'));
			} else {
				$this->error($this->M->getError().$this->M->getLastSql());
			}
		} else {
			$this->error($this->M->getError().$this->M->getLastSql());
		}

	}


	public function setEmployeeEntry(){
		$id = $_POST["id"];
		$list = M("RecruitInfo")->where(array('id'=>$id ))->select();
		if($list["0"]["retest"]==1){
			if(empty($list["0"]["quit_date"])){
				$_POST["entry_date"] = UTC_to_locale_time($_POST["entry_date"]);
				$_POST["status"] = 1;
				//$_POST["retention"] = 1;
				$re = $this->M->create($_POST, 2);
				if ($re) {
					if ($this->M->save() !== false) {
						$this->success(L('ADD_SUCCESS'));
					} else {
						$this->error($this->M->getError().$this->M->getLastSql());
					}
				} else {
					$this->error($this->M->getError().$this->M->getLastSql());
				}
			}else{
				$this->error("该员工已离职，无法更改入职日期！");
			    exit();
			}
		
		}else{
			 $this->error("只有复试通过才能入职！");
		}
	}

	public function setEmployeeQuit(){
		$id = $_POST["id"];
		$list = M("RecruitInfo")->where(array('id'=>$id ))->select();
		if(!start_end_date($list["0"]["entry_date"],UTC_to_locale_time($_POST["quit_date"]))){
			$this->error("离职日期不能小于入职日期！");
			exit();
		}
		if($list["0"]["status"]==1){
			if(empty($list["0"]["quit_date"])){
				$_POST["quit_date"] = UTC_to_locale_time($_POST["quit_date"]);
				$quit_date = UTC_to_locale_time($_POST["quit_date"]);
				$entry_date = $list["0"]["entry_date"];
				$arr = explode("-",$entry_date);
				$new_month = substr($entry_date,6,1)+1;
				$retention_date  = $arr["0"]."-0".$new_month."-".$arr["2"];
				$retention_date_strtotime = strtotime($retention_date);
				if(strtotime($quit_date)<$retention_date_strtotime){
					$_POST["status"] = 2;
				}
				$re = $this->M->create($_POST, 2);
				if ($re) {
					if ($this->M->save() !== false) {
						$this->success(L('ADD_SUCCESS'));
					} else {
						$this->error($this->M->getError().$this->M->getLastSql());
					}
				} else {
					$this->error($this->M->getError().$this->M->getLastSql());
				}
			}else{
				$this->error("该员工已离职，无法更改离职日期！");
			    exit();
			}
		
		}else{
			 $this->error("只有已经入职的才能离职！");
		}
	}

	public function setEmployeeDepartemtnItem(){
		if ($this->getRoleEname()=='gold') {
			return 1;
		} else if(session('account')['userInfo']['department_id']!=0){
			$row = $this->getDepartmentRow();
			if ($row['type']==DepartmentModel::HR_DEPARTMENT) {
				return 1;
			} 
		}
		return 0;
	}




}
